
import 'dart:convert';
import 'dart:io';

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:oktoast/oktoast.dart';
import 'package:sjx/common_ui/loading.dart';
import 'package:sjx/repository/model/task_detail_model.dart';
import 'package:sjx/route/route_utils.dart';

import '../../../repository/sjx_api.dart';

class TaskSubmitViewModel with ChangeNotifier {
  final List<File> _uploadedImages = [];
  final List<String> _uploadedImageUrls = []; // 存储上传成功的图片URL
  TaskDetailModel? _taskDetailModel;
  String _comment = '';
  bool _isLoading = true;


  List<File> get uploadedImages => _uploadedImages;
  List<String> get uploadedImageUrls => _uploadedImageUrls;
  String get comment => _comment;
  TaskDetailModel? get taskDetailModel => _taskDetailModel;
  bool get isLoading => _isLoading;

  void updateComment(String content) {
    _comment = content;
    notifyListeners();
  }

  Future<void> getTask(String taskNo) async {
    _isLoading = true;
    notifyListeners();
    try {
      _taskDetailModel = await SJXApi.instance().taskDetail(taskNo);
    } catch (e) {
      showToast('获取任务详情失败: ${e.toString()}');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> submitTask(BuildContext context) async {
    Loading.showLoading();
    try {
      // 1. 上传所有图片
      await _uploadAllImages();

      // 2. 准备提交数据
      final Map<String, dynamic> submitData = {};
      if (_uploadedImageUrls.isNotEmpty) {
        submitData['images'] = _uploadedImageUrls;
      }
      if (_comment.isNotEmpty) {
        submitData['comment'] = _comment;
      }

      // 3. 调用提交任务API (这里需要根据实际API补充)
      await SJXApi.instance().submitTask(taskDetailModel!.orderNo, submitData);

      Loading.dismissAll();
      final result = await showOkAlertDialog(
        context: context,
        title: "提交成功",
        message: "“我的-在做的任务-待审核”中查看审核进度",
        okLabel: "好的"
      );
      if (result == OkCancelResult.ok) {
        RouteUtils.pop(context);
      }
    } catch (e) {
      showToast('提交失败: ${e.toString()}');
    } finally {
      Loading.dismissAll();
      notifyListeners();
    }
  }

  Future<void> _uploadAllImages() async {
    _uploadedImageUrls.clear();

    for (final imageFile in _uploadedImages) {
      try {
        // 压缩图片
        final compressedBytes = await FlutterImageCompress.compressWithFile(
          imageFile.path,
          minWidth: 1024,
          minHeight: 1024,
          quality: 80,
        );

        if (compressedBytes == null) {
          throw Exception('图片压缩失败');
        }

        final base64Image = base64Encode(compressedBytes);

        // 调用上传接口
        final imageUrl = await SJXApi.instance().uploadImage(base64Image);
        _uploadedImageUrls.add(imageUrl);
      } catch (e) {
        showToast('图片上传失败: ${e.toString()}');
        rethrow;
      }
    }
  }
}